package com.mdd.common.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.exception.OperateException;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @name: ResponseControllerAdvice
 * @description: 全局响应处理类
 * @type: JAVA
 * @since: 2022/10/14 11:00
 * @author: slien.zuo
 */
@RestControllerAdvice(basePackages = {"com.mdd"})
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    /**
     * @param methodParameter:
     * @param aClass:
     * @name: supports
     * @description: 设置如果返回的是ResultVO，则不给予处理
     * @return: boolean
     */
    @Override
    public boolean supports(MethodParameter methodParameter, @NotNull Class<? extends HttpMessageConverter<?>> aClass) {
        return !methodParameter.getParameterType().equals(AjaxResult.class);
    }

    /**
     * @param o:
     * @param methodParameter:
     * @param mediaType:
     * @param aClass:
     * @param serverHttpRequest:
     * @param serverHttpResponse:
     * @name: beforeBodyWrite
     * @description: 对返回结果进行包装处理
     * @return: Object
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, @NotNull MediaType mediaType, @NotNull Class<? extends HttpMessageConverter<?>> aClass, @NotNull ServerHttpRequest serverHttpRequest, @NotNull ServerHttpResponse serverHttpResponse) {
        if (methodParameter.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.writeValueAsString(AjaxResult.success(o));
            } catch (JsonProcessingException e) {
                throw new OperateException("数据异常");
            }
        }
        return AjaxResult.success(o);
    }
}
